import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
import * as hooks from './hooks'

Vue.use(VueRouter)

// 参数1：你需要检索的目录  相对路径
// 参数2：检索的目录是否需要递归检索 true/false
// 参数3：指定检查返回的文件类型 正则
const moduleFn = require.context('./routes', false, /\.js$/i)
const routes = moduleFn.keys().reduce((prev, curr) => {
  let route = moduleFn(curr).default
  if (Array.isArray(route)) {
    prev.push(...route)
  } else {
    prev.push(route)
  }
  return prev
}, [])

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


//全局路由守卫用于控制底部导航栏的显示
router.beforeEach((to,from,next)=>{
  let arr = ["home","classify","mySession","person"]
  let index = arr.findIndex(i=>i==to.path.match(/(?<=\/)\w+/)[0])
  //若to路由不在底部导航显示的路由中，隐藏底部导航

  if(index<0){
    store.commit("setFootNavShow",false)
  }else{
    //否则则显示导航，并更新导航激活状态

    store.commit("setFootNavShow",true)
    store.commit("setFoorNavActive",index)

  }
  next()
})
/**
 * 引入hook进行指定页面的登录状态验证，没有登录则跳转至登录页面
 */
Object.keys(hooks).forEach(key => router.beforeEach(hooks[key]))
export default router